package com.wishwingz.klipper;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpUrlConnectionManager {
	private PrintWriter request = null;
	private HttpURLConnection conn = null;
	private BufferedReader response = null;
	private URL url;
	private String param;
	private Map<String, String> paramForMultiPart;
	private StringBuilder jsonStr;

	private String lineEnd = "\r\n";
	private String twoHyphens = "--";
	private String boundary = "*****";

	public HttpUrlConnectionManager(URL url, String param) {
		this.url = url;
		this.param = param;
	}

	public HttpUrlConnectionManager(URL url, Map<String, String> paramMap) {
		this.url = url;
		this.paramForMultiPart = paramMap;
	}

	public String httpRequest(String method) {
		try {
			conn = (HttpURLConnection)url.openConnection();

			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod(method);

			request = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));

			if (!(param.equalsIgnoreCase("")) || param != null) {
				request.println(param);
			}
			request.flush();

			response = new BufferedReader(new InputStreamReader(conn.getInputStream()));

			String str = "";
			jsonStr = new StringBuilder();

			while ((str = response.readLine()) != null) {
				jsonStr.append(str);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ConnectionCloseManager.closeInputOutput(request, response);
		}

		return jsonStr.toString();
	}

	public String httpMultipartRequest(File uploadFile) {
		DataOutputStream dos = null;

		try {
			conn = (HttpURLConnection)url.openConnection();

			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			conn.connect();

			/*
			 *  write data
			 */
			dos = new DataOutputStream(conn.getOutputStream());

			//upload text field
			this.writeField(dos);
			//upload file
			this.writeFile(dos, "file", "file", "image/png", uploadFile);
			//upload 
			dos.flush();

			/*
			 *  get response
			 */
			response = new BufferedReader(new InputStreamReader(conn.getInputStream()));

			String str = "";
			jsonStr = new StringBuilder();

			while ((str = response.readLine()) != null) {
				jsonStr.append(str);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ConnectionCloseManager.closeInputOutput(request, response);
			if (dos != null) {
				try {
					dos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return jsonStr.toString();
	}

	private void writeField(DataOutputStream dos) {
		try {
			for (String key : this.paramForMultiPart.keySet()) {
				dos.writeBytes(twoHyphens + boundary + lineEnd);
				dos.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
				dos.writeBytes(lineEnd);
				dos.writeBytes(this.paramForMultiPart.get(key));
				dos.writeBytes(lineEnd);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void writeFile(DataOutputStream dos, String fieldName, String fieldValue, String fileType, File file) {
		FileInputStream fileInputStream = null;

		try {
			if (file == null || file.exists() == false) {
				return;
			}

			fileInputStream = new FileInputStream(file);

			// opening boundary line            
			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + fieldValue + "\"" + lineEnd);
			dos.writeBytes("Content-Type: " + fileType + lineEnd);
			dos.writeBytes(lineEnd);

			// create a buffer of maximum size             
			int bytesAvailable = fileInputStream.available();
			int maxBufferSize = 1024;
			int bufferSize = Math.min(bytesAvailable, maxBufferSize);
			byte[] buffer = new byte[bufferSize];

			// read file and write it into form...             
			int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			while (bytesRead > 0) {
				dos.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}

			// closing CRLF            
			dos.writeBytes(lineEnd);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fileInputStream != null) {
				try {
					fileInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

class ConnectionCloseManager {
	public static void closeInputOutput(Writer writer, Reader reader) {
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
			}
		}
		if (writer != null) {
			try {
				writer.close();
			} catch (IOException e) {
			}
		}
	}
}
